<template>
  <div class="pieClassName">
    <div class="chart">
      <chart
        :option="refChartOption"
        :style="{ height: `${chartHeight}` }"
        v-bind="$attrs"
        @echart:click="pieClickHandle"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, PropType, ref, watch, Component } from 'vue';
import { Chart, SeriesDataItem } from '@/components';
import { EChartOption } from 'echarts';
import { getCustomOption } from './options';

export default defineComponent({
  props: {
    data: {
      type: Array as PropType<SeriesDataItem[]>,
      default: () => [],
    },
    height: {
      type: Number,
      default: 0,
    },
    fieldNames: {
      type: Object,
      default: () => ({
        name: 'name',
        value: 'value',
      }),
    },
    title: {
      type: String,
      default: '-',
    },
  },
  setup(props, { emit }) {
    const chartOption = getCustomOption();
    const refChartOption = ref(chartOption);
    const refChart = ref<null | Component>(null);

    const chartHeight = computed(() => `${props.height + 100}px`);
    const setChartOption = (data: any[]) => {
      const xAxis: string[] = [];
      const seriesData: EChartOption.SeriesPie.DataObject[] = [];
      data.forEach(item => {
        const name = item[props.fieldNames.name];
        const value = item[props.fieldNames.value];

        xAxis.push(name);
        seriesData.push({
          name,
          value,
        });
      });

      //   // 图例
      //   refChartOption.value.legend.data = xAxis;
      //   refChartOption.value.legend.formatter = (name: any) => {
      //     const [currentItem] = data.filter(item => item[props.fieldNames.name] === name);
      //     // return `${name}    ${currentItem[props.fieldNames.value]}    ${currentItem.percent}`;
      //     let arr = [
      //       '{a|' +
      //         name +
      //         '}' +
      //         '{b|' +
      //         currentItem[props.fieldNames.value] +
      //         '}' +
      //         '{c|' +
      //         currentItem.percent +
      //         '}',
      //     ];
      //     return arr;
      //   };

      // 标题
      refChartOption.value.title.text = `{value|${props.title}\n   TOP5}`;
      refChartOption.value.series[0].data = seriesData;
    };

    const pieClickHandle = e => {
      emit('zrender:click', e);
    };

    watch(
      () => props.data,
      () => {
        setChartOption(props.data);
      },
    );

    onMounted(() => {
      setChartOption(props.data);
    });
    return {
      chartHeight,
      refChartOption,
      setChartOption,
      refChart,
      pieClickHandle,
    };
  },
  components: {
    Chart,
  },
});
</script>

<style lang="less" scoped>
@import './index.less';
</style>
